﻿using MoonSharp.Interpreter;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

public class LuaBehaviour : LuaComponent
{
    static LuaBehaviour()
    {
        IEnumerator<System.Type> enumerator = typeof(LuaBehaviour).Assembly.GetTypes().Concat<System.Type>(typeof(LuaComponent).Assembly.GetTypes()).GetEnumerator();
        try
        {
            while (enumerator.MoveNext())
            {
                System.Type current = enumerator.Current;
                if (current.Name.EndsWith("Extension") || current.Name.EndsWith("Utility"))
                {
                    UserData.RegisterExtensionType(current, InteropAccessMode.Default);
                }
            }
        }
        finally
        {
            if (enumerator == null)
            {
            }
            enumerator.Dispose();
        }
        UserData.RegisterExtensionType(typeof(CoroutineExtension), InteropAccessMode.Default);
        UserData.RegisterExtensionType(typeof(GameObjectExtension), InteropAccessMode.Default);
        UserData.RegisterExtensionType(typeof(AssetExtension), InteropAccessMode.Default);
        UserData.RegisterType<LuaBehaviour>(InteropAccessMode.Default, null);
    }

    protected override void Awake()
    {
        if (LuaComponentUtility.GetScriptAsset(base.scriptFileName) == null)
        {
            base.scriptFileName = Path.ChangeExtension(this.GetModelFileName(), ".lua");
        }
        base.Awake();
    }

    public static LuaBehaviour Create(GameObject go, string scriptFileName)
    {
        return LuaComponent.Create<LuaBehaviour>(go, scriptFileName);
    }

    private static T GetEnumValue<T>(string enumName)
    {
        IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();
        try
        {
            while (enumerator.MoveNext())
            {
                object current = enumerator.Current;
                if (current.ToString() == enumName)
                {
                    return (T) current;
                }
            }
        }
        finally
        {
            IDisposable disposable = enumerator as IDisposable;
            if (disposable == null)
            {
            }
            disposable.Dispose();
        }
        return default(T);
    }

    protected override void OnCreateScript(Script script)
    {
        base.OnCreateScript(script);
        script.SetProperty("GetComponent", new Func<System.Type, Component>(this.GetComponent));
        script.SetProperty("AddComponent", new Func<System.Type, Component>(this.AddComponent));
    }
}

